package com.plugins.http;

import java.util.concurrent.TimeUnit;

import org.apache.http.client.CookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

import com.iclient.dao.DaoUtils;
import com.iclient.dao.model.MCookie;
import com.iclient.dao.service.ImgService;

/**
 * 
 * @author zziahui
 * @descp  httpclient池配置
 * @time   2015-05-29 21:42
 * 
 */
public class HttpUtils {
	public static final int ConnectionTimeOut = 2*1000;
	public static final int SocketTimeout = 2*1000;
	public static final int ConnectionRequestTimeout = 5*100;
	private static final PoolingHttpClientConnectionManager pool = new PoolingHttpClientConnectionManager();
	
	//此线程用来监控未关闭的Connection
	public static class IdleConnectionMonitorThread extends Thread{
	    private final PoolingHttpClientConnectionManager pmg;
	    private volatile boolean shutdown;
	    public IdleConnectionMonitorThread() {
	        this.pmg = pool;
	    }
	    @Override
	    public void run() {
	        try {
	            while (!shutdown) {
	                synchronized (this) {
	                    wait(5000);
	                    pmg.closeExpiredConnections();
	                    pmg.closeIdleConnections(10, TimeUnit.SECONDS);
	                }
	            }
	        } catch (InterruptedException ex) {
	        }
	    }
	    public void shutdown() {
	        shutdown = true;
	        synchronized (this) {
	            notifyAll();
	        }
	    }
	}
	
	static{
		pool.setMaxTotal(20000);
		pool.setDefaultMaxPerRoute(5000);
		IdleConnectionMonitorThread thread = new IdleConnectionMonitorThread();
		thread.start();
	}
	
	public final static CloseableHttpClient httpClient = HttpClients.custom()
			.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))
			.setConnectionManager(pool).build();
	
	public final static CookieStore getCookie(){
		ImgService imgService = (ImgService) DaoUtils.getBean("imgService");
		MCookie mcookie = imgService.findCookie("msinalogin");
		return LocalCookie.getCookie(mcookie.getContent());
	}
	
}
